import gql from "graphql-tag";
import client from "@/gql-client";
import md5 from "js-md5";
import { observable, action, runInAction } from "mobx";

/** 查询复用 */
export const query = {
  // 账号密码
  byNameAndPassword: gql`
    query login($name: bpchar, $md5Password: bpchar) {
      account(
        limit: 1,
        where: {
          name: { _eq: $name }
          _and: { password: { _eq: $md5Password } }
        }
      ) {
        id
        name
        role
      }
    }
  `,
  ById: gql`
    query user($id: Int) {
      account(
        limit: 1,
        where: { id: { _eq: $id } }
      ) {
        id
        name
        nickname
        role
        created_at
        todo_list {
          id
          title
          content
        }
      }
    }
  `
};

/** 用户账号信息 */
export let UserAccount = observable.map(
  JSON.parse(sessionStorage.getItem("userinfo") || "{}")
);
UserAccount.observe(changes => {
  let storeAccount = UserAccount.toJSON();
  delete storeAccount.todo_list;
  sessionStorage.setItem("userinfo", JSON.stringify(storeAccount));
});

/** 登出 */
export const logout = async () => {
  UserAccount.clear();
  localStorage.clear();
};

/** 获取详情 */
export const getDetail = async () => {
  try {
    const { data } = await client.query({
      query: query.ById,
      variables: {
        id: UserAccount.get('id')
      }
    });
    runInAction(() => {
      UserAccount.merge(data.account[0]);
    });
    return data.account[0];
  } catch (e) {
    console.log(e.message);
    logout();
  }
};

/**
 * 用户登录
 * @param {Object} params { name: 账号, password: 密码 }
 */
export default async params => {
  localStorage.removeItem("apollo-token");
  let headers = {
    "x-hasura-user-name": params.name
  };
  try {
    const { data } = await client.query({
      query: query.byNameAndPassword,
      variables: {
        name: params.name,
        md5Password: md5(params.password)
      },
      context: {
        headers
      }
    });
    runInAction(() => {
      UserAccount.replace(data.account[0]);
    });
    return data.account[0];
  } catch (e) {
    console.log(e.message);
  }
};
